/**
 * 网络辅助工具
 */

const app = getApp()

/**
 * 检查网络状态
 */
function checkNetworkStatus() {
  return new Promise((resolve, reject) => {
    wx.getNetworkType({
      success: (res) => {
        console.log('网络类型:', res.networkType)
        if (res.networkType === 'none') {
          wx.showToast({
            title: '网络连接失败，请检查网络设置',
            icon: 'none',
            duration: 3000
          })
          reject(new Error('网络连接失败'))
        } else {
          resolve(res.networkType)
        }
      },
      fail: () => {
        reject(new Error('获取网络状态失败'))
      }
    })
  })
}

/**
 * 显示网络错误提示
 */
function showNetworkError(error) {
  console.error('网络请求失败:', error)
  
  let title = '网络错误'
  let message = '请检查网络连接'
  
  if (error.errMsg) {
    if (error.errMsg.includes('timeout')) {
      title = '连接超时'
      message = '网络连接超时，请稍后重试'
    } else if (error.errMsg.includes('url not in domain list')) {
      title = '域名校验失败'
      message = '请在开发工具中关闭域名校验\n详情 → 本地设置 → 不校验合法域名'
    } else if (error.errMsg.includes('fail')) {
      title = '连接失败'
      message = '无法连接到服务器，请检查：\n1. 后端服务是否启动\n2. IP地址是否正确\n3. 网络是否正常'
    }
  }
  
  wx.showToast({
    title: message,
    icon: 'none',
    duration: 3000
  })
}

/**
 * 获取本机IP地址（用于真机调试）
 */
function getLocalIPTip() {
  const tip = `
真机调试提示：
1. 确保手机和电脑在同一WiFi网络
2. 将 localhost 替换为电脑的IP地址
3. 例如：http://192.168.1.100:8084/api

获取电脑IP方法：
- Windows: 命令行输入 ipconfig
- Mac: 命令行输入 ifconfig | grep inet
- 或查看网络设置中的IP地址
  `
  
  console.log(tip)
  return tip
}

/**
 * 检查开发环境网络配置
 */
function checkDevelopmentNetwork() {
  const envConfig = require('../config/env')
  
  return {
    currentEnv: envConfig.currentEnv,
    baseUrl: envConfig.baseUrl,
    availableIPs: envConfig.developmentIPs || [],
    timestamp: new Date().toLocaleString()
  }
}

/**
 * 测试网络连接
 */
function testConnection() {
  return new Promise((resolve, reject) => {
    const testUrl = `${app.globalData.baseUrl}/test`
    
    wx.request({
      url: testUrl,
      method: 'GET',
      timeout: 5000,
      success: (res) => {
        resolve({
          success: true,
          statusCode: res.statusCode,
          message: '连接成功'
        })
      },
      fail: (error) => {
        resolve({
          success: false,
          error: error.errMsg,
          message: '连接失败'
        })
      }
    })
  })
}

/**
 * 获取网络状态
 */
function getNetworkStatus() {
  return new Promise((resolve) => {
    wx.getNetworkType({
      success: (res) => {
        resolve({
          networkType: res.networkType,
          isConnected: res.networkType !== 'none'
        })
      },
      fail: () => {
        resolve({
          networkType: 'unknown',
          isConnected: false
        })
      }
    })
  })
}

/**
 * 显示网络诊断信息
 */
async function showNetworkDiagnostic() {
  const networkStatus = await getNetworkStatus()
  const envInfo = checkDevelopmentNetwork()
  
  let content = `网络类型: ${networkStatus.networkType}\n`
  content += `连接状态: ${networkStatus.isConnected ? '已连接' : '未连接'}\n`
  content += `当前环境: ${envInfo.currentEnv}\n`
  content += `API地址: ${envInfo.baseUrl}\n`
  content += `检查时间: ${envInfo.timestamp}`
  
  wx.showModal({
    title: '网络诊断',
    content: content,
    showCancel: false,
    confirmText: '确定'
  })
}

module.exports = {
  checkNetworkStatus,
  showNetworkError,
  getLocalIPTip,
  checkDevelopmentNetwork,
  testConnection,
  getNetworkStatus,
  showNetworkDiagnostic
} 